package edu.hawaii.duedates.webapp;

import org.apache.wicket.Page;
import org.apache.wicket.Request;
import org.apache.wicket.Response;
import org.apache.wicket.Session;
import org.apache.wicket.authorization.strategies.page.SimplePageAuthorizationStrategy;
import org.apache.wicket.protocol.http.WebApplication;
import edu.hawaii.duedates.datastore.DueDatesConfig;
import edu.hawaii.duedates.configuration.ConfigurationManager;

/**
 * Application object for the DueDates application.
 * 
 * @author Daniel Arakaki, Jeho Jung, Arthur Shum, Daniel Tian.
 */
public class DueDatesApplication extends WebApplication {

  private final DueDatesConfig config;
    
  /**
   * The default constructor. Automatically called by Jetty.
   */
  public DueDatesApplication() {
    ConfigurationManager cm = new ConfigurationManager();
    this.config = cm.getDueDatesConfig();
  }

  /**
   * A constructor for starting the application with a specified configuration that is not read in
   * from ~/.duedates/duedates.xml.
   * 
   * @param config An instance of DueDatesConfig.
   */
  public DueDatesApplication(DueDatesConfig config) {
    this.config = config;
  }
  
  /**
   * Return the home page for this application.
   * 
   * @return The home page.
   */
  @Override
  public Class<? extends Page> getHomePage() {
    return LoginPage.class;
  }

  /**
   * Automatically called by Wicket to create a session object to hold the models for each user of
   * this application.
   * 
   * @param request The HTTP request.
   * @param response The HTTP response.
   * @return The session instance for this user.
   */
  @Override
  public Session newSession(Request request, Response response) {
    DueDatesSession mySession = new DueDatesSession(request);
    mySession.setDueDatesConfig(this.config);    
    return mySession;
    //return new DueDatesSession(request);
  }

  /**
   * Configures application security settings so that only users that are logged-in can access 
   * secure web page (classes that extend SecurePage), and users that are not logged-in are 
   * redirected to the login page.
   * 
   * From the Wicket Javadoc: http://wicket.apache.org/docs/wicket-1.3.2/wicket/apidocs/index.html
   */
  @Override
  protected void init() {    
    getSecuritySettings().setAuthorizationStrategy(
        new SimplePageAuthorizationStrategy(SecurePage.class, LoginPage.class) {
          // Every time a user attempts to access a secure web page, the application checks the 
          // session to see if the user is logged-in.
          protected boolean isAuthorized() {
            return ((DueDatesSession) Session.get()).isLoggedIn();
          }
        });
  }
  
}
